﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Diagnostics;

namespace GenBenEditor
{
    class TgaLoader
    {
        private struct TgaHeader
        {
            public byte id_length;
            public byte color_map_type;
            public byte image_type;
            public UInt16 color_map_index;
            public UInt16 color_map_length;
            public byte color_map_entry_size;
            public UInt16 x_origin;
            public UInt16 y_origin;
            public UInt16 width;
            public UInt16 height;
            public byte pixel_depth;
            public byte image_descriptor;

            public TgaHeader(BinaryReader reader)
            {
                id_length = reader.ReadByte();
                color_map_type = reader.ReadByte();
                image_type = reader.ReadByte();
                color_map_index = reader.ReadUInt16();
                color_map_length = reader.ReadUInt16();
                color_map_entry_size = reader.ReadByte();
                x_origin = reader.ReadUInt16();
                y_origin = reader.ReadUInt16();
                width = reader.ReadUInt16();
                height = reader.ReadUInt16();
                pixel_depth = reader.ReadByte();
                image_descriptor = reader.ReadByte();
            }
        }

        public static Bitmap FromFile(string path)
        {
            FileStream input = new FileStream(path, FileMode.Open);
            BinaryReader reader = new BinaryReader(input);

            TgaHeader header = new TgaHeader(reader);

            Debug.Assert(header.color_map_type == 0);
            Debug.Assert(header.image_type == 2);
            Debug.Assert(header.pixel_depth == 32 || header.pixel_depth == 24);

            input.Seek(header.id_length, SeekOrigin.Current);

            Bitmap result = new Bitmap(header.width, header.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            if (header.pixel_depth == 24)
            {
                for (int pixel = 0; pixel < (header.width * header.height); ++pixel)
                {
                    byte[] color = reader.ReadBytes(3);
                    result.SetPixel(pixel % header.width, header.height - pixel / header.width - 1, 
                        Color.FromArgb(color[2], color[1], color[0]));
                }
            }
            else
            {
                for (int pixel = 0; pixel < (header.width * header.height); ++pixel)
                {
                    byte[] color = reader.ReadBytes(4);
                    result.SetPixel(pixel % header.width, header.height - pixel / header.width - 1, 
                        Color.FromArgb(color[3], color[2], color[1], color[0]));
                }
            }

            reader.Close();
            return result;
        }
    }
}
